#!/bin/bash
QEMU_MONITOR="/tmp/qemu-monitor"

function qemu_plug_usb() {
  echo "drive_add 0 file=device/qemu/aarch64/usb-disk.raw,if=none,id=usbdrive" | sudo socat - UNIX-CONNECT:${QEMU_MONITOR}
  echo "device_add usb-storage,bus=xhci.0,drive=usbdrive,id=usb1" | sudo socat - UNIX-CONNECT:${QEMU_MONITOR}
}

function qemu_unplug_usb() {
  echo "device_del usb1" | sudo socat - UNIX-CONNECT:${QEMU_MONITOR}
}

function qemu_quit() {
  echo "quit" | sudo socat - UNIX-CONNECT:${QEMU_MONITOR}
}

function qemu_copy() {
  PLATFORM=$1
  TARGET_IMAGE="device/qemu/$PLATFORM/rootfs.ext4"

  if [ ! -f "$TARGET_IMAGE" ]; then
    echo "Error: Target image $TARGET_IMAGE does not exist"
    return 1
  fi

  # 检查镜像是否可以正常挂载
  echo "Checking if the image can be mounted..."
  if ! sudo e2fsck -n "$TARGET_IMAGE" &>/dev/null; then
    echo "Error: The image file system is corrupted or cannot be mounted"
    return 1
  fi

  echo "Checking if root directory is accessible..."
  if ! sudo e2ls "$TARGET_IMAGE:/" &>/dev/null; then
    echo "Error: Cannot access root directory of the image"
    return 1
  fi

  # 使用固定路径配置（后续添加新路径只需在此数组新增条目）
  local directories_to_copy=(
    "./device/qemu/app:/app"        # 主程序目录
    "./out/web:/app/web"            # 资源目录
    "./out/bin:/app/bin"   # 资源目录
  )

  # 统一处理所有需要复制的目录
  for entry in "${directories_to_copy[@]}"; do
    local src="${entry%%:*}"
    local dst="${entry##*:}"

    if [ -d "$src" ]; then
      copy_to_image "$src" "$dst" "$TARGET_IMAGE"
    else
      echo "Note: Source directory $src does not exist, skipping..."
    fi
  done

  echo "Checking and repairing file system after copying..."
  sudo e2fsck -fy "$TARGET_IMAGE"

  # 强制卸载文件系统
  echo "Forcing unmount of the file system..."
  sudo umount -f /tmp/mnt 2>/dev/null || true

  echo "File copying completed for $PLATFORM"
}

# 新增通用复制函数
function copy_to_image() {
  local src_dir="$1"
  local target_path="$2"
  local image="$3"

  echo "Starting to copy $src_dir to $image:$target_path"

  # 删除旧目录时需要逐级处理
  echo "Deleting old $target_path directory..."
  sudo e2rm -rf "$image:$target_path" 2>/dev/null || true

  # 修改目录创建方式（使用手动逐级创建）
  local current_path=""
  IFS='/' read -ra ADDR <<<"$target_path"
  for i in "${ADDR[@]}"; do
    [ -z "$i" ] && continue
    current_path="$current_path/$i"
    if ! sudo e2mkdir "$image:$current_path" 2>/dev/null; then
      echo "Note: Directory $current_path already exists"
    fi
  done

  # 执行递归复制
  copy_recursive "$src_dir" "$target_path" "$image"
}

# 修改后的递归复制函数（移除重复的目录创建逻辑）
function copy_recursive() {
  local src="$1"
  local dst="$2"
  local image="$3"

  for item in "$src"/*; do
    local name=$(basename "$item")
    if [ -d "$item" ]; then
      # 仅创建当前层级目录
      if ! sudo e2mkdir "$image:$dst/$name" 2>/dev/null; then
        echo "Note: Directory $dst/$name already exists"
      fi
      copy_recursive "$item" "$dst/$name" "$image"
    elif [ -f "$item" ]; then
      if ! sudo e2cp "$item" "$image:$dst/$name"; then
        echo "Error: Failed to copy $item to $dst/$name"
      else
        echo "Copied: $item to $dst/$name"
      fi
    fi
  done
}

function qemu_run() {
  PLATFORM=$1
  case $PLATFORM in
  m64x86)
    sudo qemu-system-x86_64 -M pc -kernel device/qemu/m64x86/bzImage \
      -drive file=device/qemu/m64x86/rootfs.ext2,if=virtio,format=raw \
      -append "rootwait root=/dev/vda console=tty1 console=ttyS0" \
      -serial stdio -net nic,model=virtio -net user
    ;;
  aarch64)
    sudo qemu-system-aarch64 -M virt -cpu cortex-a53 -nographic -smp 2 -m 1024 \
      -kernel device/qemu/aarch64/Image \
      -append "rootwait root=/dev/vda console=ttyAMA0" \
      -netdev bridge,id=eth0,br=br0 -device virtio-net-device,netdev=eth0 \
      -drive file=device/qemu/aarch64/rootfs.ext4,if=none,format=raw,id=hd0 \
      -device virtio-blk-device,drive=hd0 \
      -device qemu-xhci,id=xhci \
      -monitor unix:/tmp/qemu-monitor,server,nowait \
      -no-shutdown \
      -serial mon:stdio
    ;;
  *)
    echo "Error: Unsupported platform for QEMU: $PLATFORM"
    exit 1
    ;;
  esac
}

function qemu_monitor() {
  sudo socat - UNIX-CONNECT:/tmp/qemu-monitor
}
